package com.liufeng.myheart.config;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.liufeng.myheart.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OfflineMapActivity extends AppCompatActivity implements MKOfflineMapListener, ExpandableListView.OnChildClickListener, AdapterView.OnItemClickListener, ExpandableListView.OnGroupClickListener {

    private MKOfflineMap mOffline = null;
    private EditText cityNameView;
    /**
     * 已下载的离线地图信息列表
     */
    private ArrayList<MKOLUpdateElement> localMapList = null;
    private LocalMapAdapter lAdapter = null;
    ArrayList<Map<String, Object>> allgroupCities;
    List<List<Map<String, Object>>> allchildCities;
    Map<String, Object> curCityMap;
    SimpleExpandableListAdapter aAdapter;
    int cityid;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            ArrayList<MKOLSearchRecord> records2 = null;
            if (cityNameView.getText().toString().equals("")) {
                records2 = mOffline.getOfflineCityList();
            } else {
                records2 = mOffline.searchCity(cityNameView.getText().toString());
            }
            if (records2 != null) {
                allgroupCities.clear();
                allchildCities.clear();
                for (MKOLSearchRecord r : records2) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("info", r.cityName + "(" + r.cityID + ")" + "   --"
                            + OfflineMapActivity.this.formatDataSize(r.size));
                    map.put("id", r.cityID);
                    allgroupCities.add(map);
                    List<Map<String, Object>> childs = new ArrayList<>();
                    if (r.cityType == 1) {
                        for (MKOLSearchRecord child : r.childCities) {
                            Map<String, Object> childmap = new HashMap<>();
                            childmap.put("info", child.cityName + "(" + child.cityID + ")" + "   --"
                                    + OfflineMapActivity.this.formatDataSize(child.size));
                            childmap.put("id", child.cityID);
                            childs.add(childmap);
                        }
                    }
                    allchildCities.add(childs);
                }
                aAdapter.notifyDataSetChanged();
            }

        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline);
        setTitle("离线地图下载");
        mOffline = new MKOfflineMap();
        mOffline.init(this);
        initView();

    }

    private void initView() {

        cityNameView = (EditText) findViewById(R.id.city);
        cityNameView.addTextChangedListener(textWatcher);

        TextView curCity = (TextView) findViewById(R.id.curCity);
        ArrayList<Map<String, Object>> hotCities = new ArrayList<>();
        // 获取当前城市列表
        ArrayList<MKOLSearchRecord> records1 = mOffline.searchCity("保定市");
        if (records1 != null) {
            MKOLSearchRecord r = records1.get(0);
            curCityMap = new HashMap<>();
            curCityMap.put("info", r.cityName + "(" + r.cityID + ")" + "   --"
                    + this.formatDataSize(r.size));
            curCityMap.put("id", r.cityID);

        }
        curCity.setText(curCityMap.get("info").toString());
        curCity.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                cityid = (Integer) curCityMap.get("id");
                start(cityid);
            }
        });
        ExpandableListView allCityList = (ExpandableListView) findViewById(R.id.allcitylist);
        // 获取所有支持离线地图的城市
        allgroupCities = new ArrayList<>();
        allchildCities = new ArrayList<>();
        ArrayList<MKOLSearchRecord> records2 = mOffline.getOfflineCityList();
        if (records2 != null) {
            for (MKOLSearchRecord r : records2) {
                Map<String, Object> map = new HashMap<>();
                map.put("info", r.cityName + "(" + r.cityID + ")" + "   --"
                        + this.formatDataSize(r.size));
                map.put("id", r.cityID);
                allgroupCities.add(map);
                List<Map<String, Object>> childs = new ArrayList<>();
                if (r.cityType == 1) {
                    for (MKOLSearchRecord child : r.childCities) {
                        Map<String, Object> childmap = new HashMap<>();
                        childmap.put("info", child.cityName + "(" + child.cityID + ")" + "   --"
                                + this.formatDataSize(child.size));
                        childmap.put("id", child.cityID);
                        childs.add(childmap);
                    }
                }
                allchildCities.add(childs);
            }
        }
        aAdapter = new SimpleExpandableListAdapter(this, allgroupCities, android.R.layout.simple_expandable_list_item_1, new String[]{"info"}, new int[]{android.R.id.text1}
                , allchildCities, android.R.layout.simple_list_item_1, new String[]{"info"}, new int[]{android.R.id.text1});
        allCityList.setAdapter(aAdapter);
        allCityList.setOnChildClickListener(this);
        allCityList.setOnGroupClickListener(this);
        LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
        LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
        lm.setVisibility(View.GONE);
        cl.setVisibility(View.VISIBLE);

        // 获取已下过的离线地图信息
        localMapList = mOffline.getAllUpdateInfo();
        if (localMapList == null) {
            localMapList = new ArrayList<MKOLUpdateElement>();
        }

        ListView localMapListView = (ListView) findViewById(R.id.localmaplist);
        lAdapter = new LocalMapAdapter();
        localMapListView.setAdapter(lAdapter);

    }

    /**
     * 切换至城市列表
     *
     * @param view
     */
    public void clickCityListButton(View view) {
        LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
        LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
        lm.setVisibility(View.GONE);
        cl.setVisibility(View.VISIBLE);

    }

    /**
     * 切换至下载管理列表
     *
     * @param view
     */
    public void clickLocalMapListButton(View view) {
        LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
        LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
        lm.setVisibility(View.VISIBLE);
        cl.setVisibility(View.GONE);
    }

    /**
     * 搜索离线需市
     *
     * @param view
     */
    public void search(View view) {
        ArrayList<MKOLSearchRecord> records = mOffline.searchCity(cityNameView
                .getText().toString());
        if (records == null || records.size() != 1) {
            return;
        }
    }

    /**
     * 开始下载
     */
    public void start(int cityid) {
        mOffline.start(cityid);
        clickLocalMapListButton(null);
        Toast.makeText(this, "开始下载离线地图", Toast.LENGTH_SHORT)
                .show();
        updateView();
    }

    /**
     * 暂停下载
     *
     * @param view
     */
    public void stop(View view) {
        mOffline.pause(cityid);
        Toast.makeText(this, "暂停下载离线地图. cityid: " + cityid, Toast.LENGTH_SHORT)
                .show();
        updateView();
    }

    /**
     * 删除离线地图
     *
     * @param view
     */
    public void remove(View view) {
        mOffline.remove(cityid);
        Toast.makeText(this, "删除离线地图. cityid: " + cityid, Toast.LENGTH_SHORT)
                .show();
        updateView();
    }

    /**
     * 更新状态显示
     */
    public void updateView() {
        localMapList = mOffline.getAllUpdateInfo();
        if (localMapList == null) {
            localMapList = new ArrayList<MKOLUpdateElement>();
        }
        lAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        MKOLUpdateElement temp = mOffline.getUpdateInfo(cityid);
        if (temp != null && temp.status == MKOLUpdateElement.DOWNLOADING) {
            mOffline.pause(cityid);
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public String formatDataSize(int size) {
        String ret = "";
        if (size < (1024 * 1024)) {
            ret = String.format("%dK", size / 1024);
        } else {
            ret = String.format("%.1fM", size / (1024 * 1024.0));
        }
        return ret;
    }

    @Override
    protected void onDestroy() {
        /**
         * 退出时，销毁离线地图模块
         */
        mOffline.destroy();
        super.onDestroy();
    }

    @Override
    public void onGetOfflineMapState(int type, int state) {
        switch (type) {
            case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
                MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                // 处理下载进度更新提示
                if (update != null) {

                    updateView();
                }
            }
            break;
            case MKOfflineMap.TYPE_NEW_OFFLINE:
                // 有新离线地图安装
                Log.d("OfflineMapActivity", String.format("add offlinemap num:%d", state));
                break;
            case MKOfflineMap.TYPE_VER_UPDATE:
                // 版本更新提示
                // MKOLUpdateElement e = mOffline.getUpdateInfo(state);

                break;
            default:
                break;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Map<String, Object> map = (Map<String, Object>) parent.getItemAtPosition(position);
        cityid = (Integer) map.get("id");
        start(cityid);
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

        Map<String, Object> map = (Map<String, Object>) aAdapter.getChild(groupPosition, childPosition);
        cityid = (Integer) map.get("id");
        start(cityid);
        return true;
    }

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
        if (aAdapter.getChildrenCount(groupPosition) == 0) {
            Map<String, Object> map = (Map<String, Object>) aAdapter.getGroup(groupPosition);
            cityid = (Integer) map.get("id");
            start(cityid);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 离线地图管理列表适配器
     */
    public class LocalMapAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return localMapList.size();
        }

        @Override
        public Object getItem(int index) {
            return localMapList.get(index);
        }

        @Override
        public long getItemId(int index) {
            return index;
        }

        @Override
        public View getView(int index, View view, ViewGroup arg2) {
            MKOLUpdateElement e = (MKOLUpdateElement) getItem(index);
            view = View.inflate(OfflineMapActivity.this,
                    R.layout.item_offline_localmap, null);
            initViewItem(view, e);
            return view;
        }

        void initViewItem(View view, final MKOLUpdateElement e) {
            Button remove = (Button) view.findViewById(R.id.remove);
            final Button pause = (Button) view.findViewById(R.id.pause);
            final Button start = (Button) view.findViewById(R.id.start);
            TextView title = (TextView) view.findViewById(R.id.title);
            TextView update = (TextView) view.findViewById(R.id.update);
            TextView ratio = (TextView) view.findViewById(R.id.ratio);
            ratio.setText(e.ratio + "%");
            title.setText(e.cityName);
            if (e.update) {
                update.setText("可更新");
            } else {
                update.setText("最新");
            }
            if (e.status == MKOLUpdateElement.SUSPENDED) {
                pause.setVisibility(View.GONE);
                start.setVisibility(View.VISIBLE);
            }
            if (e.status == MKOLUpdateElement.DOWNLOADING) {
                start.setVisibility(View.GONE);
                pause.setVisibility(View.VISIBLE);
            }
            if (e.status == MKOLUpdateElement.FINISHED) {
                start.setVisibility(View.GONE);
                pause.setVisibility(View.GONE);
            }

            remove.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    mOffline.remove(e.cityID);
                    updateView();
                }
            });
            pause.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    mOffline.pause(e.cityID);
                    updateView();
                }
            });
            start.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    mOffline.start(e.cityID);
                    updateView();
                }
            });


        }

    }


}